//
//  LeveyPopListView.m
//  LeveyPopListViewDemo
//
//  Created by Levey on 2/21/12.
//  Copyright (c) 2012 Levey. All rights reserved.
//

#import "LeveyPopListView.h"
#import "LeveyPopListViewCell.h"

#define POPLISTVIEW_SCREENINSET 16
#define POPLISTVIEW_HEADER_HEIGHT 50.
#define RADIUS 5.

@interface LeveyPopListView (private)
- (void)fadeIn;
- (void)fadeOut;
@end

@implementation LeveyPopListView
@synthesize delegate;
@synthesize name;
@synthesize typeName;
@synthesize fullHeight;
@synthesize back;
@synthesize selectedIndex;
@synthesize selectedTypeIndex;
@synthesize clickedType;
@synthesize listName;
#pragma mark - initialization & cleaning up
- (id)initWithTitle:(NSString *)aTitle options:(NSArray *)aOptions fullHeight: (int)height
{
    fullHeight = height;
    return [self initWithTitle:aTitle options:aOptions];
}

- (id)initWithTitle:(NSString *)aTitle options:(NSArray *)aOptions
{
    if(fullHeight==0)
        fullHeight = 120;
    CGRect rect = [[UIScreen mainScreen] applicationFrame];
    if (self = [super initWithFrame:CGRectMake(rect.origin.x,rect.origin.y+10,rect.size.width,rect.size.height-fullHeight)])
    {
//        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//        [[NSNotificationCenter defaultCenter] addObserver:self
//                                                 selector:@selector(redrawComponent)
//                                                     name:@"test"
//                                                   object:nil];

        self.backgroundColor = [UIColor clearColor];

        _title = [aTitle copy];
        _options = [aOptions copy];
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(POPLISTVIEW_SCREENINSET, 
                                                                   POPLISTVIEW_SCREENINSET + POPLISTVIEW_HEADER_HEIGHT,
                                                                   rect.size.width - 2 * POPLISTVIEW_SCREENINSET,
                                                                   rect.size.height - 2 * POPLISTVIEW_SCREENINSET - POPLISTVIEW_HEADER_HEIGHT - RADIUS-fullHeight)];
        _tableView.separatorColor = [UIColor colorWithRed:1 green:147/255 blue:48/255 alpha:.1];//[UIColor colorWithWhite:0 alpha:.2];
        _tableView.backgroundColor = [UIColor whiteColor];
        
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [self setExtraCellLineHidden:_tableView];
        [self addSubview:_tableView];

    }
    return self;    
}

- (id)initWithTitle:(NSString *)aTitle options:(NSArray *)aOptions types:(NSArray *)aTypes fullHeight:(int)height
{
    fullHeight = height;
    return [self initWithTitle:aTitle options:aOptions types:aTypes];
}

- (id)initWithTitle:(NSString *)aTitle options:(NSArray *)aOptions types:(NSArray *)aTypes
{
    if(fullHeight==0)
        fullHeight = 120;
    CGRect rect = [[UIScreen mainScreen] applicationFrame];
    if (self = [super initWithFrame:CGRectMake(rect.origin.x,rect.origin.y+10,rect.size.width,rect.size.height-fullHeight)])
    {
        //        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        //        [[NSNotificationCenter defaultCenter] addObserver:self
        //                                                 selector:@selector(redrawComponent)
        //                                                     name:@"test"
        //                                                   object:nil];
        
        self.backgroundColor = [UIColor clearColor];
        
        _title = [aTitle copy];
        
        _optionsType = [aTypes copy];
        
        _tableViewType = [[UITableView alloc] initWithFrame:CGRectMake(POPLISTVIEW_SCREENINSET,
                                                                   POPLISTVIEW_SCREENINSET + POPLISTVIEW_HEADER_HEIGHT-2,
                                                                   (rect.size.width - 2 * POPLISTVIEW_SCREENINSET)/2,
                                                                   rect.size.height - 2 * POPLISTVIEW_SCREENINSET - POPLISTVIEW_HEADER_HEIGHT - RADIUS-fullHeight+2)];
        _tableViewType.separatorColor = LINE_COLOR;// [UIColor colorWithRed:1 green:147/255 blue:48/255 alpha:.1];//[UIColor colorWithWhite:0 alpha:.2];
        _tableViewType.backgroundColor = [UIColor whiteColor];
        
        _tableViewType.dataSource = self;
        _tableViewType.delegate = self;
        [self setExtraCellLineHidden:_tableViewType];
        [self addSubview:_tableViewType];

        _options = [aOptions copy];
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(POPLISTVIEW_SCREENINSET+(rect.size.width - 2 * POPLISTVIEW_SCREENINSET)/2,                                                                 POPLISTVIEW_SCREENINSET + POPLISTVIEW_HEADER_HEIGHT-2,
                                                                   (rect.size.width - 2 * POPLISTVIEW_SCREENINSET)/2,
                                                                   rect.size.height - 2 * POPLISTVIEW_SCREENINSET - POPLISTVIEW_HEADER_HEIGHT - RADIUS-fullHeight+2)];
        _tableView.separatorColor = [UIColor clearColor];//[UIColor colorWithRed:1 green:147/255 blue:48/255 alpha:.1];//[UIColor colorWithWhite:0 alpha:.2];
//        _tableView.backgroundColor =  [UIColor colorWithRed: 227/255 green: 227/255 blue: 227/225 alpha: 0.1 ];
        _tableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gray.png"]];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        //
        [self setExtraCellLineHidden:_tableView];
        [self addSubview:_tableView];
        
    }
    return self;    
}

//- (void)redrawComponent
//{
//    [self setNeedsDisplay];
//}

#pragma mark - Private Methods
- (void)fadeIn
{
    self.transform = CGAffineTransformMakeScale(1.3, 1.3);
    self.alpha = 0;
    [UIView animateWithDuration:.15 animations:^{
        self.alpha = 1;
        self.transform = CGAffineTransformMakeScale(1, 1);
    }];

}
- (void)fadeOut
{
    [UIView animateWithDuration:.15 animations:^{
        self.transform = CGAffineTransformMakeScale(1.3, 1.3);
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        if (finished) {
            [self removeFromSuperview];
        }
    }];
}

#pragma mark - Instance Methods
- (void)showInView:(UIView *)aView animated:(BOOL)animated
{
    clickedType = selectedTypeIndex;

    back = [[UIView alloc]initWithFrame:CGRectMake(0,0,320,560)];
    back.backgroundColor = [UIColor colorWithRed: .3 green: .3 blue: .3 alpha: .4];
    [aView addSubview:back];
    [aView addSubview:self];
    if (animated) {
        [self fadeIn];
    }
}

#pragma mark - Tableview datasource & delegates
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView==_tableViewType)
        return [_optionsType count];
    else
        return [_options count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView==_tableViewType){
        static NSString *cellIdentity = @"PopListViewCell";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentity];
        if (cell ==  nil) {
            cell = [[LeveyPopListViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity];
        }
        int row = [indexPath row];
        
        cell.imageView.image = [[_optionsType objectAtIndex:row] objectForKey:@"img"];
        cell.textLabel.text = [[_optionsType objectAtIndex:row] objectForKey:typeName];
        [cell setSelectedTextColor:[UIColor blackColor]];
        [cell setSelectedBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"choose_item_selected.jpg"]]];
        if (row==selectedTypeIndex) {
            cell.selected=true;
            [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        }
        return cell;
    }else{
        static NSString *cellIdentity = @"PopListViewCell";
        
        LeveyPopListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentity];
        if (cell ==  nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"PopCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        }
        int row = [indexPath row];
        if(clickedType ==selectedTypeIndex && row==selectedIndex)
            cell.imageSelected.image = [UIImage imageNamed:@"ic_checked.png" ];
        cell.lbText.text = [[_options objectAtIndex:row] objectForKey:name];
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==_tableViewType) {
//        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        int row = [indexPath row];
        //记录选中行id
        clickedType = row;
//        selectedTypeIndex = row;
        NSDictionary *dic=[_optionsType objectAtIndex:row];
        _options = [[dic objectForKey:listName] copy];
        [_tableView reloadData];
    }else{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
        selectedTypeIndex=clickedType;
    // tell the delegate the selection
    if (self.delegate && [self.delegate respondsToSelector:@selector(leveyPopListView:didSelectedIndex:options:didSelectedTypeIndex:)]) {
        [self.delegate leveyPopListView:self didSelectedIndex:[indexPath row] options:_options didSelectedTypeIndex:selectedTypeIndex];
    }
    [back removeFromSuperview];
    // dismiss self
    [self fadeOut];
    }
}
#pragma mark - TouchTouchTouch
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    // tell the delegate the cancellation
    if (self.delegate && [self.delegate respondsToSelector:@selector(leveyPopListViewDidCancel)]) {
        [self.delegate leveyPopListViewDidCancel];
    }
    [back removeFromSuperview];
    // dismiss self
    [self fadeOut];
}

#pragma mark - DrawDrawDraw
- (void)drawRect:(CGRect)rect
{
    CGRect bgRect = CGRectInset(rect, POPLISTVIEW_SCREENINSET, POPLISTVIEW_SCREENINSET);
    CGRect titleRect = CGRectMake(POPLISTVIEW_SCREENINSET + 10, POPLISTVIEW_SCREENINSET + 10 + 5,
                                  rect.size.width -  2 * (POPLISTVIEW_SCREENINSET + 10), 30);
    
    CGRect separatorRect = CGRectMake(POPLISTVIEW_SCREENINSET, POPLISTVIEW_SCREENINSET + POPLISTVIEW_HEADER_HEIGHT - 2,
                                      rect.size.width - 2 * POPLISTVIEW_SCREENINSET, 2);
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // Draw the background with shadow
    CGContextSetShadowWithColor(ctx, CGSizeZero, 6., [UIColor colorWithWhite:0 alpha:1].CGColor);
//    [[UIColor colorWithWhite:1 alpha:.85] setFill];
    UIColor* lightColor = TEXTFIELD_HOTCOLOR;//[UIColor colorWithRed: 1 green: .5764 blue: .1882 alpha: 1];
    [lightColor setFill];
//    [[UIColor colorWithRed: 1 green: .5764 blue: .1882 alpha: 1] setFill];
    float x = POPLISTVIEW_SCREENINSET;
    float y = POPLISTVIEW_SCREENINSET;
    float width = bgRect.size.width;
    float height = bgRect.size.height;
    
    
//    UIColor* lightColor = [UIColor colorWithRed: 0 green: 0 blue: 0 alpha: 0.15];
    
    CGMutablePathRef path = CGPathCreateMutable();
	CGPathMoveToPoint(path, NULL, x, y + RADIUS);
	CGPathAddArcToPoint(path, NULL, x, y, x + RADIUS, y, RADIUS);
	CGPathAddArcToPoint(path, NULL, x + width, y, x + width, y + RADIUS, RADIUS);
	CGPathAddArcToPoint(path, NULL, x + width, y + height, x + width - RADIUS, y + height, RADIUS);
	CGPathAddArcToPoint(path, NULL, x, y + height, x, y + height - RADIUS, RADIUS);
	CGPathCloseSubpath(path);
	CGContextAddPath(ctx, path);
    CGContextFillPath(ctx);
    CGPathRelease(path);
    
    // Draw the title and the separator with shadow
    CGContextSetShadowWithColor(ctx, CGSizeMake(0, 0), 0,[UIColor colorWithRed: 1 green: 1 blue: 1 alpha: 1].CGColor);
    [[UIColor colorWithWhite:1 alpha:1] setFill];

//    [[UIColor colorWithRed:1 green:147/255 blue:48/255 alpha:.75] setFill];
    [_title drawInRect:titleRect withFont:[UIFont systemFontOfSize:16.]];
    CGContextFillRect(ctx, separatorRect);
}

- (void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}
/**
 
 画图形渐进色方法，此方法只支持双色值渐变
 @param context     图形上下文的CGContextRef
 @param clipRect    需要画颜色的rect
 @param startPoint  画颜色的起始点坐标
 @param endPoint    画颜色的结束点坐标
 @param options     CGGradientDrawingOptions
 @param startColor  开始的颜色值
 @param endColor    结束的颜色值
 */
- (void)DrawGradientColor:(CGContextRef)context
                     rect:(CGRect)clipRect
                    point:(CGPoint) startPoint
                    point:(CGPoint) endPoint
                  options:(CGGradientDrawingOptions) options
               startColor:(UIColor*)startColor
                 endColor:(UIColor*)endColor
{
    UIColor* colors [2] = {startColor,endColor};
    CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
    CGFloat colorComponents[8];
    
    for (int i = 0; i < 2; i++) {
        UIColor *color = colors[i];
        CGColorRef temcolorRef = color.CGColor;
        
        const CGFloat *components = CGColorGetComponents(temcolorRef);
        for (int j = 0; j < 4; j++) {
            colorComponents[i * 4 + j] = components[j];
        }
    }
    
    CGGradientRef gradient =  CGGradientCreateWithColorComponents(rgb, colorComponents, NULL, 2);
    
    CGColorSpaceRelease(rgb);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, options);
    CGGradientRelease(gradient);
}
@end
